/*
 * @Author: yangzonglong
 * @Date: 2021-03-09 16:03:48
 * @version: v1.0.0
 * @Descripttion: 处理select radio 选项设置
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-17 09:24:44
 * @Auditor:
 */
import React, { useState, useCallback, useEffect } from 'react';
import uuidv4 from 'uuid-v4';
import { Select } from '@library';
import { Modal, Button, Row, Col, Input } from 'antd';
import Icon from './../../../icon/Icon';
import styles from './style.module.scss';

const ConditionDataSource = [
  {
    label: '等于',
    value: 'equal',
    id: '1',
  },
  {
    label: '不等于',
    value: '$ne',
    id: '2',
  },
  {
    label: '包含',
    value: '$like',
    id: '3',
  },
  {
    label: '不包含',
    value: '$nin',
    id: '4',
  },
];
interface ScreenModalProps {
  dataSource: any[];
  fieldNames?: any[];
  moduleName?: any[];
  visible: boolean;
  onOK: (data: any) => void;
  onCancel: () => void;
}

interface DataSourceProps {
  id?: string;
  dataSource: {
    field?: string;
    condition?: string;
    keyword?: string;
    id?: string;
  }[];
}

interface SelectProps {
  value?: string;
  dataSource?: any[];
  onChange?: (val?: string, key?: string) => void;
}

const getDefaultInnerLine = () => ({
  field: undefined,
  condition: undefined,
  keyword: undefined,
  id: uuidv4(),
});

const getDefaultLine = () => ({
  id: uuidv4(),
  dataSource: [getDefaultInnerLine()],
});

const SelectKey = (props: SelectProps) => {
  return (
    <Select
      style={{ width: '100%' }}
      placeholder="请选择字段"
      value={props.value}
      onSelect={(e: any) => props?.onChange?.(e + '', 'field')}
      fieldNames={{ value: 'value', label: 'label' }}
      url=""
      dataSource={props?.dataSource || []}
    />
  );
};

const SelectCondition = (props: SelectProps) => {
  return (
    <Select
      style={{ width: '100%' }}
      value={props.value}
      placeholder="判断符号"
      onSelect={(e: any) => props?.onChange?.(e + '', 'condition')}
      fieldNames={{ value: 'value', label: 'label' }}
      url=""
      dataSource={ConditionDataSource}
    />
  );
};

const getDataSource = (allSource: any[], selectSource: any[], selftKey: string) => {
  let _selectSource = selectSource.map((item) => item.field);
  return allSource.filter((item) => selftKey === item.value || !_selectSource.includes(item.value));
};

const ScreenModal = (props: ScreenModalProps) => {
  const [dataSource, setDataSource] = useState<DataSourceProps[]>([]);

  // const _moduleName = useMemo(() => {
  //   return props.fieldNames.map((item) => ({ value: item, label: item }));
  // }, [props.fieldNames]);

  useEffect(() => {
    if (props.dataSource?.length) {
      setDataSource(props.dataSource);
    } else {
      setDataSource([getDefaultLine()]);
    }
  }, [props.dataSource]);

  const onChange = useCallback(
    (index?: number, i?: number, key?: string, val?: string) => {
      setDataSource(
        dataSource.map((item, _index) => {
          if (_index === index) {
            return {
              ...item,
              dataSource: item.dataSource.map((ele, _i) => {
                return _i === i ? { ...ele, [key!]: val } : ele;
              }),
            };
          }
          return item;
        })
      );
    },
    [dataSource]
  );

  const onDelete = useCallback(
    (index?: number, i?: number) => {
      let _dataSource = dataSource.map((item, _index) => {
        return _index === index ? { ...item, dataSource: item.dataSource.filter((ele, _i) => _i !== i) } : item;
      });
      setDataSource(_dataSource.filter((item) => item?.dataSource?.length));
    },
    [dataSource]
  );
  const addNewOr = useCallback(
    (i?: number) => {
      setDataSource(
        dataSource.map((item, index) => {
          return i === index ? { ...item, dataSource: [...item.dataSource, getDefaultInnerLine()] } : item;
        })
      );
    },
    [dataSource]
  );
  const addNewAnd = useCallback((i?: number) => setDataSource([...dataSource, getDefaultLine()]), [dataSource]);

  return (
    <Modal
      maskClosable={false}
      destroyOnClose
      width={640}
      title="筛选数据"
      visible={props.visible}
      onOk={() => props.onOK?.(dataSource)}
      onCancel={() => props.onCancel?.()}
    >
      {dataSource.map((item, index) => {
        return (
          <>
            <div className={styles.div} key={item.id}>
              {item.dataSource.map((ele, i) => {
                return (
                  <Row>
                    <Col span={8}>
                      <SelectKey
                        onChange={(val?: string, key?: string) => onChange(index, i, key, val)}
                        value={ele.field}
                        dataSource={getDataSource(props.fieldNames || [], item.dataSource || [], ele.field!)}
                      />
                    </Col>
                    <Col span={5}>
                      <SelectCondition onChange={(val?: string, key?: string) => onChange(index, i, key, val)} value={ele.condition} />
                    </Col>
                    <Col span={8}>
                      <Input placeholder="请输入" value={ele.keyword} onChange={(e) => onChange(index, i, 'keyword', e.target.value)} />
                    </Col>
                    <Col span={2} className={styles.col} onClick={() => onDelete(index, i)}>
                      <Icon icon="&#xe666;" />
                    </Col>
                  </Row>
                );
              })}
              <Button className={styles.btnStyle} icon={<Icon icon="&#xe635;" />} block onClick={() => addNewOr(index)}>
                添加且条件
              </Button>
            </div>
            {index !== dataSource.length - 1 && <p className={styles.p}>或</p>}
          </>
        );
      })}
      <Button className={styles.addStyle} block onClick={() => addNewAnd()}>
        添加或条件
      </Button>
    </Modal>
  );
};

export default ScreenModal;
